package com.springbootx.outlogs.async.impl;

import com.springbootx.outlogs.async.AsyncService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.util.CollectionUtils;
import org.thymeleaf.util.StringUtils;

import javax.websocket.Session;
import java.io.*;
import java.util.Arrays;
import java.util.Map;

/**
 * @author Tony.niu (hystrix0779@yeah.net)
 * @version V1.0
 * @date 2020/7/11
 **/
@Configuration
public class AsyncServiceImpl implements AsyncService {

    public static final Logger log = LoggerFactory.getLogger(AsyncServiceImpl.class);

    @Value("${spring.application.name}")
    private String applicationName;


    @Override
    @Async("taskExecutor")
    public void readLogs(Map<String, Session> sessionMap,Session session,Map<String, Integer> lengthMap) throws IOException {
        log.info("LoggingWebSocketServer 任务开始");
        String srcFilename = "/Users/niulixiong/Documents/apache-tomcat-9.0.35/logs/catalina.out";
        String charset = "UTF-8";
        InputStream fileInputStream = new FileInputStream(srcFilename);
        fileInputStream.skip(1);
        boolean first = true;
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream, charset));
        while (sessionMap.get(session.getId()) != null) {
            BufferedReader reader = null;
            try {
//                //日志文件路径，获取最新的
//                //字符流
//                Object[] lines = bufferedReader.lines().toArray();
//                //对日志进行着色，更加美观  PS：注意，这里要根据日志生成规则来操作
//                for (int i = 0; i < lines.length; i++) {
//                    String line = (String) lines[i];
//                    //先转义
//                    line = line.replaceAll("&", "&amp;")
//                            .replaceAll("<", "&lt;")
//                            .replaceAll(">", "&gt;")
//                            .replaceAll("\"", "&quot;");
//                    //处理等级
//                    line = line.replace("DEBUG", "<span style='color: blue;'>DEBUG</span>");
//                    line = line.replace("INFO", "<span style='color: green;'>INFO</span>");
//                    line = line.replace("WARN", "<span style='color: orange;'>WARN</span>");
//                    line = line.replace("ERROR", "<span style='color: red;'>ERROR</span>");
//
//                    //处理类名
//                    String[] split = line.split("]");
//                    if (split.length >= 2) {
//                        String[] split1 = split[1].split("-");
//                        if (split1.length >= 2) {
//                            line = split[0] + "]" + "<span style='color: #298a8a;'>" + split1[0] + "</span>" + "-" + split1[1];
//                        }
//                    }
//                    lines[i] = line;
//                }
                //日志文件路径，获取最新的
                String filePath = srcFilename;

                //字符流
                reader = new BufferedReader(new FileReader(filePath));
                Object[] lines = reader.lines().toArray();

                //只取从上次之后产生的日志
                Object[] copyOfRange = Arrays.copyOfRange(lines, lengthMap.get(session.getId()), lines.length);

                //对日志进行着色，更加美观  PS：注意，这里要根据日志生成规则来操作
                for (int i = 0; i < copyOfRange.length; i++) {
                    String line = (String) copyOfRange[i];
                    //先转义
                    line = line.replaceAll("&", "&amp;")
                            .replaceAll("<", "&lt;")
                            .replaceAll(">", "&gt;")
                            .replaceAll("\"", "&quot;");

                    //处理等级
                    line = line.replace("DEBUG", "<span style='color: blue;'>DEBUG</span>");
                    line = line.replace("INFO", "<span style='color: green;'>INFO</span>");
                    line = line.replace("WARN", "<span style='color: orange;'>WARN</span>");
                    line = line.replace("ERROR", "<span style='color: red;'>ERROR</span>");

                    //处理类名
                    String[] split = line.split("]");
                    if (split.length >= 2) {
                        String[] split1 = split[1].split("-");
                        if (split1.length >= 2) {
                            line = split[0] + "]" + "<span style='color: #298a8a;'>" + split1[0] + "</span>" + "-" + split1[1];
                        }
                    }

                    copyOfRange[i] = line;
                }

                //存储最新一行开始
                lengthMap.put(session.getId(), lines.length);

                //第一次如果太大，截取最新的200行就够了，避免传输的数据太大
                if(first && copyOfRange.length > 200){
                    copyOfRange = Arrays.copyOfRange(copyOfRange, copyOfRange.length - 200, copyOfRange.length);
                    first = false;
                }
                if (!CollectionUtils.isEmpty(Arrays.asList(copyOfRange))) {
                    String result = StringUtils.join(copyOfRange, "<br/>");
                    send(session, result);
                }
                //休眠一秒
                Thread.sleep(1000);
            } catch (Exception e) {
                //捕获但不处理
                e.printStackTrace();
            }
        }
        log.info("LoggingWebSocketServer 任务结束");
    }

    void test(){

    }
    /**
     * 封装一个send方法，发送消息到前端
     */
    public void send(Session session, String message) {
        try {
            session.getBasicRemote().sendText(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException, InterruptedException {

    }
}

